/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_ui.htm
 *
 * Zhiqim UI is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
 
+(function(Z)
{//BEGIN
// @version v1.1.0 @author zouzhigang 2015-11-12 新建与整理
        
// 调用举例:
// var clip = new Z.Clipboard();
// clip.id = "clip_button";
// clip.onClick = function(){clip.setText(Z('#text').val());};
// clip.onCompleted = function(){alert("成功复制代码到剪贴板！");};
// clip.execute();

Z.Clipboard = Z.Class.newInstance();
Z.Clipboard.v = "8.0.4";
/****************************************/
//定义Z.Clipboard下缓存和Flash事件方法
/****************************************/
Z.Clipboard.cache = new Z.HashMap();
Z.Clipboard.load = function(id)
{//加载成功
    if (!id || !Z.Clipboard.cache.containsKey(id))
        return;
        
    Z.Clipboard.cache.get(id).load();
};
Z.Clipboard.click = function(id)
{//鼠标点击开始（传入复制文本）
    if (!id || !Z.Clipboard.cache.containsKey(id))
        return;
        
    return Z.Clipboard.cache.get(id).onClick();
};
Z.Clipboard.complete = function(id, text)
{//鼠标点击完成（完成复制回调）
    if (!id || !Z.Clipboard.cache.containsKey(id))
        return;
        
    Z.Clipboard.cache.get(id).complete(text);
};

/****************************************/
//定义Z.Clipboard下的原型属性和方法
/****************************************/
Z.Clipboard.prototype = 
{
    defaults:
    {
        //公共参数
        elem: null,
        onClick: null,
        onCompleted: null,
        
        //H5参数
        text: null,
        
        //Flash参数
        flash: false,
        flashPath: null,
        contextPath: null,
        background: "transparent",
        opacity: 1
    },
    
    init: function()
    {
        this.ready = false;
    },
    
    execute: function()
    {
        this.$elem = Z.$elem(this.elem, "Z.Clipboard");
        if (!Z.T.isFunction(this.onClick))
        {//必须的函数
            Z.alert("[Z.Clipboard]的[onClick]参数必须是函数");
            return;
        }
        
        if (!this.flash && document.execCommand)
        {//未强制flash，且支持执行命令的，默认使用H5
            this.$elem.click(this.doClick, this);
        }
        else
        {//否则默认Flash
            //创建一个DIV覆盖该元素
            var left = this.$elem.offsetLeft();
            var top = this.$elem.offsetTop();
            var width = this.$elem.offsetWidth();
            var height = this.$elem.offsetHeight();
            var zIndex = this.$elem.css("zIndex");
            zIndex = Z.V.isInteger(zIndex)?parseInt(zIndex)+1:99;
            
            this.$flashDiv = Z("<div>").appendToPos(this.$elem.parent())
                .css({position: "absolute", top: top, left: left, width: width, height: height, zIndex: zIndex})
                .css("backgroundColor", this.background).opacity(this.opacity);
            
            //获取Flash对象
            this.flashId = "Z_Clipboard_"+Z.random(10);
            var flashVars = "flashId="+this.flashId;
            var flashPath = Z.rootPath(this.contextPath, this.flashPath || "/service/res/swf/ZClipboard.swf");
            
            if (Z.B.msieOnly)
            {//ie10以前
                this.$flashDiv.html('<object id="'+this.flashId+'" name="'+this.flashId+'" width="'+width+'" height="'+height+'" align="middle" classid="clsid:d27cdb6e-ae6d-11cz-96b8-444553540000" codebase="'+Z.L.protocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+flashPath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashVars+'"/><param name="wmode" value="transparent"/></object>');
            }
            else
            {//firefox,chrome,trident
                this.$flashDiv.html('<embed id="'+this.flashId+'" name="'+this.flashId+'" src="'+flashPath+'" flashvars="'+flashVars+'" pluginspage="'+Z.L.protocol+'://www.macromedia.com/go/getflashplayer" style="z-index:999;width:100%;height:100%" align="middle" border="0" loop="false" menu="false" quality="best" bgcolor="#ffffff" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" wmode="transparent"></embed>');
            }
            
            this.flashObj = Z.D.id(this.flashId);
            Z.Clipboard.cache.put(this.flashId, this);
        }
    },
    
    setText: function(text)
    {//设置复制文本
        if (!this.flash && document.execCommand)
            this.text = text;
        else
            this.ready && this.flashObj.setText(text);
    },
    
    doClick: function()
    {//H5复制文本
    
        //1.先回调点击函数
        var text = this.onClick.call(this);
        if (text && Z.T.isString(text)){
            this.text = text;
        }
        
        //2.创建一个文本域固定在顶端隐藏，
        var $textarea = Z("<textarea></textarea>")
            .addClass("z-hidden-fixed").text(this.text)
            .appendTo("body");
            
        //3.选中文本域内容，执行复制命令
        $textarea.select();
        document.execCommand("copy");
        
        //4.最后回调成功函数
        this.complete(this.text);
    },
    
    load: function()
    {//Flash加载完成
        this.ready = true;
    },
    
    complete: function(text)
    {//复制完成
        Z.T.isFunction(this.onCompleted) && this.onCompleted.call(this, text);
    },
    
    remove: function()
    {
        if (!this.flash && document.execCommand)
            this.$elem.offclick(this.doClick, this);
        else
        {
            Z.Clipboard.cache.remove(this.flashId);
            this.$flashDiv.remove();
        }
    }
};

/********************************************/
//刷新静态函数和第一次加载
/********************************************/
Z.Clipboard.oncache = [];
Z.Clipboard.onload = function()
{
    //1.先删除原来的缓存
    Z.each(Z.Clipboard.oncache, function(clipboard){
        clipboard.remove();
    });
    Z.Clipboard.oncache = [];
    
    //2.再加载所有的下拉列表
    var elements = Z.D.attrs("data-role", "z-clipboard");
    if (!elements || elements.length == 0){
        return;
    }

    Z.each(elements, function(elem)
    {
        if (!Z.EL.has(elem, "data-click"))
            return;
            
        var $elem = Z(elem);
        if ($elem.attr("type") == "submit"){
            $elem.attr("type", "button");
        }
            
        var clipboard = new Z.Clipboard();
        clipboard.elem = elem;
        clipboard.onClick = Z.evals($elem.attr("data-click"));
        clipboard.onCompleted = Z.evals($elem.attr("data-completed"));
        clipboard.flash = "true" == $elem.attr("data-flash");
        clipboard.flashPath = $elem.attr("data-flashPath");
        clipboard.contextPath = $elem.attr("data-context");
        clipboard.execute();
        
        Z.Clipboard.oncache.push(clipboard);
    });
};

Z.onload(Z.Clipboard.onload);

//END
})(zhiqim);